import React, { useState, useEffect, useRef } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  SafeAreaView, 
  TouchableOpacity, 
  ScrollView, 
  TextInput,
  Dimensions,
  Image,
  StatusBar,
  Modal,
  TouchableWithoutFeedback,
  ActivityIndicator,
  Alert,
  Linking
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { WebView } from 'react-native-webview';

const { width } = Dimensions.get('window');

// 在组件外部定义URL清理函数，以便在整个文件中使用
const cleanUrl = (url: string): string => {
  // 1. 移除无效字符和首尾空格
  let cleaned = url.replace(/[\s"'<>{}()[\]]/g, '').trim();
  
  // 2. 强制移除所有协议头
  cleaned = cleaned.replace(/https?:\/\//gi, '');
  
  // 3. 修复域名中的常见错误
  cleaned = cleaned.replace(/chat-pptcom/g, 'chat-ppt.com');
  
  // 4. 确保不以'/'或'//'开头，然后添加 https://
  if (cleaned.startsWith('//')) {
    cleaned = 'https:' + cleaned;
  } else if (cleaned.length > 0 && !cleaned.startsWith('/')) {
    cleaned = 'https://' + cleaned;
  }
  
  // 5. 去除末尾标点
  cleaned = cleaned.replace(/[.,;:?!]+$/, '');
  
  // 6. 最终检查，确保没有 http://https:// 这样的组合残留
  if (cleaned.match(/^https?:\/\/https?:\/\//i)) {
    const path = cleaned.replace(/^(https?:\/\/)+/i, '');
    cleaned = 'https://' + path;
  }
  
  return cleaned;
};

// 检查URL是否是PPT网站
const isPPTUrl = (url: string): boolean => {
  const lowerUrl = url.toLowerCase();
  return (
    lowerUrl.includes('chat-ppt.com') || 
    lowerUrl.includes('office.com') || 
    lowerUrl.includes('.ppt') ||
    lowerUrl.includes('presentation')
  );
};

// 获取移动版本URL
const getMobileUrl = (url: string): string => {
  if (!url || url.trim() === '') {
    return 'about:blank';
  }
  
  try {
    // 清理URL确保它是有效的
    let mobileUrl = cleanUrl(url);
    
    // 针对chat-ppt.com特殊处理
    if (mobileUrl.includes('chat-ppt.com')) {
      try {
        const urlObj = new URL(mobileUrl);
        
        // 如果是generateResults地址，直接返回，不要转换成view地址
        if (urlObj.pathname.includes('generateResults')) {
          return mobileUrl;
        }
        
        // 支持不同格式的URL路径
        let docId = '';
        
        // 从路径部分提取
        const pathParts = urlObj.pathname.split('/').filter(p => p);
        if (pathParts.length > 0) {
          docId = pathParts[pathParts.length - 1];
          
          if (docId && docId.length > 5) {
            // 始终使用view路径
            return `https://chat-ppt.com/view/${docId}?t=${Date.now()}`;
          }
        }
      } catch (e) {
        console.error('URL解析失败:', e);
      }
    }
    
    return mobileUrl;
  } catch (e) {
    // 返回原始URL，避免完全失败
    return url;
  }
};

const PptGenerationScreen = () => {
  const navigation = useNavigation();
  const [theme, setTheme] = useState('');
  const [selectedStyleId, setSelectedStyleId] = useState(1);
  const [quality, setQuality] = useState('优质');
  const [modalVisible, setModalVisible] = useState(false);
  const [tempQuality, setTempQuality] = useState('优质');
  
  // 内容长度相关状态
  const [contentLength, setContentLength] = useState('内容常规，20页以下');
  const [contentModalVisible, setContentModalVisible] = useState(false);
  const [tempContentLength, setTempContentLength] = useState('内容常规，20页以下');
  
  // 生成PPT相关状态
  const [isGenerating, setIsGenerating] = useState(false);
  const [pptUrl, setPptUrl] = useState('');
  const [showPreview, setShowPreview] = useState(false);
  
  // 重定向计数器
  const redirectCountRef = useRef(0);
  
  // 内容长度选项
  const contentLengthOptions = [
    '内容精简，15页以下',
    '内容常规，20页以下',
    '内容丰富，30页以下'
  ];
  
  // PPT风格数据
  const pptStyles = [
    { 
      id: 1, 
      name: '科技动感', 
      previewContent: {
        title: '标题',
        subtitle: 'Scientific and technological future'
      },
      bgColor: '#000000',
      textColor: '#FFFFFF',
      image: '🌍'
    },
    { 
      id: 2, 
      name: '乙已如意', 
      previewContent: {
        title: '标题',
        subtitle: 'HAPPY NEW YEAR!'
      },
      bgColor: '#D3302F',
      textColor: '#FFFFFF',
      image: '🐉'
    },
    { 
      id: 3, 
      name: '腾飞2025', 
      previewContent: {
        title: '标题',
        subtitle: 'HAPPY NEW YEAR!'
      },
      bgColor: '#191970',
      textColor: '#FFFFFF',
      image: '✨'
    },
    { 
      id: 4, 
      name: '大学通用', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#FFB74D',
      textColor: '#4A4A4A',
      image: '👩‍🎓'
    },
    { 
      id: 5, 
      name: '工作汇报', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#6A7FDB',
      textColor: '#FFFFFF',
      image: '📊'
    },
    { 
      id: 6, 
      name: '红色党建', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#D32F2F',
      textColor: '#FFFFFF',
      image: '⭐'
    },
    { 
      id: 7, 
      name: '论文答辩', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#FAFAFA',
      textColor: '#333333',
      image: '📝'
    },
    { 
      id: 8, 
      name: '商务经典', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#2962FF',
      textColor: '#FFFFFF',
      image: '📈'
    },
    { 
      id: 9, 
      name: '小组作业', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#4A6FE3',
      textColor: '#FFFFFF',
      image: '👨‍👩‍👧‍👦'
    },
    { 
      id: 10, 
      name: '蓝色简约', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#0277BD',
      textColor: '#FFFFFF',
      image: '🔷'
    },
    { 
      id: 11, 
      name: '未来时尚', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#000000',
      textColor: '#FFFFFF',
      image: '🌌'
    },
    { 
      id: 12, 
      name: '结课汇报', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#43A047',
      textColor: '#FFFFFF',
      image: '🎓'
    },
    { 
      id: 13, 
      name: '蓝色商务', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#01579B',
      textColor: '#FFFFFF',
      image: '🏢'
    },
    { 
      id: 14, 
      name: '活力四射', 
      previewContent: {
        title: '标题'
      },
      bgColor: '#26C6DA',
      textColor: '#333333',
      image: '🎨'
    },
  ];

  const [retryCount, setRetryCount] = useState(0);
  const [shouldReload, setShouldReload] = useState(false);
  const webViewRef = useRef<WebView>(null);

  // 重试加载的计时器
  useEffect(() => {
    if (shouldReload && retryCount < 3) {
      const timer = setTimeout(() => {
        console.log(`尝试重新加载(${retryCount + 1}/3)...`);
        if (webViewRef.current) {
          // @ts-ignore
          webViewRef.current.reload();
        }
        setRetryCount(retryCount + 1);
        setShouldReload(false);
      }, 5000); // 5秒后重试
      
      return () => clearTimeout(timer);
    }
  }, [shouldReload, retryCount]);

  const handleStyleSelect = (id: number) => {
    setSelectedStyleId(id);
  };
  
  const handleQualitySelect = (selectedQuality: string) => {
    setTempQuality(selectedQuality);
  };
  
  const handleOpenModal = () => {
    setTempQuality(quality);
    setModalVisible(true);
  };
  
  const handleConfirm = () => {
    setQuality(tempQuality);
    setModalVisible(false);
  };
  
  // 内容长度选择相关函数
  const handleContentLengthSelect = (selectedLength: string) => {
    setTempContentLength(selectedLength);
  };
  
  const handleOpenContentModal = () => {
    setTempContentLength(contentLength);
    setContentModalVisible(true);
  };
  
  const handleContentConfirm = () => {
    setContentLength(tempContentLength);
    setContentModalVisible(false);
  };
  
  // 获取内容长度值（仅数字部分）
  const getContentLengthValue = () => {
    if (contentLength.includes('15页')) return 15;
    if (contentLength.includes('20页')) return 20;
    if (contentLength.includes('30页')) return 30;
    return 20; // 默认值
  };
  
  // 生成PPT的函数
  const handleGeneratePPT = async () => {
    // 检查标题是否为空
    if (!theme.trim()) {
      Alert.alert('提示', '请输入PPT主题');
      return;
    }
    
    // 设置生成状态
    setIsGenerating(true);
    setShowPreview(false);
    setPptUrl('');
    
    try {
      // 获取选中风格
      const selectedStyle = pptStyles.find(style => style.id === selectedStyleId);
      const styleId = selectedStyle ? selectedStyle.name : '科技动感';
      
      console.log('开始生成PPT，主题:', theme, '风格:', styleId, '内容长度:', contentLength);
      
      // 使用长超时时间，确保有足够时间获取完整响应
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 10 * 60 * 1000); // 10分钟超时
      
      // 构建请求参数 - 使用流式请求
      const requestData = {
        "bot_id": "7488601842851872794",
        "user_id": "123123***", // 使用固定用户ID
        "stream": true, // 使用流式请求，以便处理多个响应
        "auto_save_history": true,
        "additional_messages": [
          {
            "role": "user",
            "content": `使用"${styleId}"风格，效果"${quality}"，${contentLength}，为我生成一个主题为"${theme}"的PPT。`,
            "content_type": "text"
          }
        ]
      };
      
      console.log('发送流式请求...');
      
      // 发送请求，使用流式响应
      const response = await fetch('https://api.coze.cn/v3/chat', {
        method: 'POST',
        headers: {
          "Authorization": "Bearer pat_72lCfOZdDlQRo5YET5kK2w4ookRhbO4oqRGQCaq7BwxfxzP9TTgRQLca6pxzWjNE",
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData),
        signal: controller.signal
      });
      
      if (!response.ok) {
        clearTimeout(timeoutId);
        throw new Error(`HTTP错误! 状态: ${response.status}`);
      }
      
      console.log('响应成功，开始处理流式数据');
      
      // 获取响应文本，因为React Native环境可能不支持getReader()流处理
      const responseText = await response.text();
      console.log('获取到响应文本，长度:', responseText.length);
      
      // 解析流式响应，将文本按行分割
      const lines = responseText.split('\n');
      console.log(`检测到${lines.length}行响应数据`);
      
      let pptLink = null;
      let foundAnswer = false;
      
      // 遍历每一行响应
      for (const line of lines) {
        if (!line.trim() || !line.startsWith('data:')) continue;
        
        try {
          // 提取JSON数据
          const jsonStr = line.substring(5).trim();
          console.log('处理响应行:', jsonStr.substring(0, 50) + '...');
          
          const data = JSON.parse(jsonStr);
          
          // 检查是否是answer类型消息
          if (data.type === 'answer') {
            console.log('找到answer类型响应');
            foundAnswer = true;
            
            // 尝试解析content字段（可能是JSON字符串）
            if (data.content) {
              console.log('处理answer.content:', data.content.substring(0, 100) + '...');
              
              try {
                // 尝试将content解析为JSON对象
                const contentObj = JSON.parse(data.content);
                console.log('成功将content解析为JSON对象');
                
                // 直接从fileInfo中提取jumpLink
                if (contentObj.fileInfo && contentObj.fileInfo.jumpLink) {
                  pptLink = contentObj.fileInfo.jumpLink;
                  console.log('从fileInfo.jumpLink提取到链接:', pptLink);
                  break;
                }
                
                // 尝试其他可能的字段
                if (contentObj.jumpLink) {
                  pptLink = contentObj.jumpLink;
                  console.log('从jumpLink直接提取到链接:', pptLink);
                  break;
                }
              } catch (e) {
                console.warn('解析content为JSON失败，尝试其他方法:', e);
                
                // 从content中查找链接的函数
                const findLink = (text: string): string | null => {
                  // 方法1: 直接搜索URL
                  const urlMatches = text.match(/(https?:\/\/[^\s"'<>()[\]]+)/g);
                  if (urlMatches) {
                    for (const url of urlMatches) {
                      if (url.includes('ppt') || url.includes('office') || url.includes('presentation')) {
                        return url;
                      }
                    }
                  }
                  
                  // 方法2: 查找JSON对象
                  try {
                    const jsonMatches = text.match(/\{[\s\S]*?\}/g);
                    if (jsonMatches) {
                      for (const match of jsonMatches) {
                        try {
                          const obj = JSON.parse(match);
                          if (obj.jumpLink) return obj.jumpLink;
                          if (obj.fileInfo && obj.fileInfo.jumpLink) return obj.fileInfo.jumpLink;
                          if (obj.url) return obj.url;
                          if (obj.link) return obj.link;
                        } catch (e) {
                          // 继续尝试下一个匹配
                        }
                      }
                    }
                  } catch (e) {
                    console.warn('解析JSON失败', e);
                  }
                  
                  return null;
                };
                
                // 尝试从内容中提取链接
                const link = findLink(data.content);
                if (link) {
                  console.log('在answer响应中找到PPT链接:', link);
                  pptLink = link;
                  break; // 找到链接后跳出循环
                }
              }
            }
          } else {
            console.log('收到非answer类型响应:', data.type || '未知类型');
          }
        } catch (e) {
          console.error('解析响应行失败:', e);
          // 继续处理下一行
        }
      }
      
      // 如果没有通过type=answer找到链接，尝试再次搜索整个响应
      if (!pptLink) {
        console.log('未从answer类型消息中找到链接，尝试搜索整个响应');
        
        // 尝试搜索整个响应文本
        const urlMatches = responseText.match(/(https?:\/\/[^\s"'<>()[\]]+)/g);
        if (urlMatches && urlMatches.length > 0) {
          console.log(`在完整响应中找到${urlMatches.length}个URL`);
          
          for (const url of urlMatches) {
            if (url.includes('ppt') || url.includes('office') || url.includes('presentation')) {
              console.log('在完整响应中找到PPT链接:', url);
              pptLink = url;
              break;
            }
          }
        }
        
        // 如果还是找不到，尝试搜索JSON对象
        if (!pptLink) {
          const jsonMatches = responseText.match(/\{[\s\S]*?\}/g);
          if (jsonMatches && jsonMatches.length > 0) {
            console.log(`在完整响应中找到${jsonMatches.length}个JSON对象`);
            
            for (const match of jsonMatches) {
              try {
                const obj = JSON.parse(match);
                if (obj.jumpLink) {
                  pptLink = obj.jumpLink;
                  console.log('从JSON对象中提取到jumpLink:', pptLink);
                  break;
                } else if (obj.fileInfo && obj.fileInfo.jumpLink) {
                  pptLink = obj.fileInfo.jumpLink;
                  console.log('从fileInfo.jumpLink中提取到链接:', pptLink);
                  break;
                }
              } catch (e) {
                // 继续尝试下一个匹配
              }
            }
          }
        }
      }
      
      clearTimeout(timeoutId);
      
      // 处理最终结果
      if (pptLink) {
        console.log('处理最终PPT链接:', pptLink);
        
        // 确保链接干净且有效
        const finalCleanedUrl = cleanUrl(pptLink);
        console.log('清理后的最终URL:', finalCleanedUrl);
        
        try {
          // 验证URL
          new URL(finalCleanedUrl);
          
          // 确保它是一个PPT相关URL
          if (isPPTUrl(finalCleanedUrl)) {
            console.log('URL有效且为PPT相关链接，设置预览');
            // 存储原始jumpLink地址，不经过getMobileUrl处理转换
            setPptUrl(finalCleanedUrl);
            setShowPreview(true);
          } else {
            console.warn('URL不是PPT相关链接:', finalCleanedUrl);
            Alert.alert('提示', '获取的PPT链接格式有误，请重试');
          }
        } catch (e) {
          console.error('URL格式无效:', e);
          Alert.alert('提示', '获取的PPT链接格式无效，请重试');
        }
      } else {
        console.warn('未能找到PPT链接');
        if (foundAnswer) {
          console.log('foundAnswer为true但未找到链接，响应内容片段:', 
            responseText.substring(0, 300));
          Alert.alert('提示', '生成PPT成功，但未能提取到链接，请重试');
        } else {
          Alert.alert('提示', '未收到完整PPT生成结果，请稍后重试');
        }
      }
    } catch (error) {
      const err = error as Error;
      console.error('生成PPT请求错误:', err.name, err.message);
      if (err.name === 'AbortError') {
        console.error('请求超时被中止');
        Alert.alert('提示', '生成PPT超时，请稍后重试');
      } else {
        Alert.alert('提示', `生成PPT失败：${err.message}`);
      }
    } finally {
      setIsGenerating(false);
    }
  };

  // 添加打开外部浏览器的函数
  const openInBrowser = (url: string) => {
    if (!url) return;
    
    // 获取移动版本URL并在浏览器中打开
    const mobileUrl = getMobileUrl(url);
    console.log('在外部浏览器中打开:', mobileUrl);
    
    Linking.canOpenURL(mobileUrl)
      .then(supported => {
        if (supported) {
          Linking.openURL(mobileUrl);
        } else {
          console.error('无法打开链接:', mobileUrl);
          Alert.alert('提示', '无法在浏览器中打开该链接');
        }
      })
      .catch(err => {
        console.error('打开链接出错:', err);
        Alert.alert('提示', '打开浏览器失败，请稍后重试');
      });
  };

  // 添加WebView状态管理
  const [isWebViewLoaded, setIsWebViewLoaded] = useState(false);
  const [webViewKey, setWebViewKey] = useState('ppt-webview-1');

  return (
    <SafeAreaView style={styles.container}>
      {/* 头部导航栏 */}
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()} style={styles.backButton}>
          <Text style={styles.backButtonText}>{'<'}</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>PPT生成</Text>
      </View>

      {/* 内容区域 */}
      <ScrollView style={styles.scrollView}>
        {/* 输入主题 */}
        <View style={styles.inputSection}>
          <Text style={styles.sectionTitle}>输入主题<Text style={styles.required}>*</Text></Text>
          <TextInput
            style={styles.themeInput}
            placeholder="请输入标题或主题"
            value={theme}
            onChangeText={setTheme}
          />
        </View>

        {/* 效果选择 */}
        <TouchableOpacity 
          style={styles.qualitySection}
          onPress={handleOpenModal}
        >
          <Text style={styles.sectionTitle}>效果</Text>
          <View style={styles.qualitySelector}>
            <Text style={styles.qualitySelectorText}>{quality}</Text>
            <Text style={styles.qualitySelectorArrow}>{'>'}</Text>
          </View>
        </TouchableOpacity>

        {/* 内容长度选择 */}
        <TouchableOpacity 
          style={styles.lengthSection}
          onPress={handleOpenContentModal}
        >
          <Text style={styles.sectionTitle}>内容&长度</Text>
          <View style={styles.lengthSelector}>
            <Text style={styles.lengthSelectorText}>{contentLength}</Text>
            <Text style={styles.lengthSelectorArrow}>{'>'}</Text>
          </View>
        </TouchableOpacity>

        {/* PPT风格选择 */}
        <View style={styles.styleSection}>
          <Text style={styles.sectionTitle}>PPT风格<Text style={styles.required}>*</Text></Text>
          <View style={styles.styleGrid}>
            {pptStyles.map((style) => (
              <TouchableOpacity 
                key={style.id}
                style={[
                  styles.styleItem,
                  selectedStyleId === style.id && styles.selectedStyleItem
                ]}
                onPress={() => handleStyleSelect(style.id)}
              >
                <View 
                  style={[
                    styles.styleImageContainer,
                    { backgroundColor: style.bgColor }
                  ]}
                >
                  {style.id === 1 && (
                    <View style={styles.techPreview}>
                      <Text style={[styles.techPreviewTitle, {color: style.textColor}]}>Scientific and technological future</Text>
                      <Text style={[styles.techPreviewSubtitle, {color: style.textColor}]}>标题</Text>
                      <Text style={[styles.techPreviewIcon, {color: style.textColor}]}>{style.image}</Text>
                    </View>
                  )}
                  {style.id === 2 && (
                    <View style={styles.chineseStylePreview}>
                      <Text style={[styles.chineseStyleTitle, {color: style.textColor}]}>标题</Text>
                      <View style={styles.chineseStyleLine}></View>
                      <Text style={[styles.chineseStyleSubtitle, {color: style.textColor}]}>HAPPY NEW YEAR!</Text>
                    </View>
                  )}
                  {style.id === 3 && (
                    <View style={styles.newYearPreview}>
                      <Text style={[styles.newYearTitle, {color: style.textColor}]}>标题</Text>
                      <Text style={[styles.newYearSubtitle, {color: style.textColor}]}>HAPPY NEW YEAR!</Text>
                      <Text style={[styles.newYearBigText, {color: style.textColor}]}>腾飞2025</Text>
                    </View>
                  )}
                  {style.id === 4 && (
                    <View style={styles.collegePreview}>
                      <Text style={[styles.collegeTitle, {color: style.textColor}]}>标题</Text>
                      <Text style={[styles.collegeIcon, {color: style.textColor}]}>{style.image}</Text>
                    </View>
                  )}
                  {style.id > 4 && (
                    <View style={styles.generalPreview}>
                      <Text style={[styles.generalPreviewTitle, {color: style.textColor}]}>标题</Text>
                      <Text style={[styles.generalPreviewIcon, {color: style.textColor}]}>{style.image}</Text>
                    </View>
                  )}
                </View>
                <Text style={styles.styleName}>{style.name}</Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
        
        {/* PPT预览区域 */}
        {showPreview && pptUrl ? (
          <View style={styles.previewSection}>
            <View style={styles.previewHeader}>
              <Text style={styles.sectionTitle}>PPT预览</Text>
              <TouchableOpacity 
                style={styles.openBrowserButton}
                onPress={() => openInBrowser(pptUrl)}
              >
                <Text style={styles.openBrowserText}>在浏览器中打开</Text>
              </TouchableOpacity>
            </View>
            
            <View style={{height: Dimensions.get('window').height * 0.7, borderWidth: 1, borderColor: '#EEEEEE', overflow: 'hidden'}}>
              {!isWebViewLoaded && (
                <View style={[styles.loaderContainer, {position: 'absolute', zIndex: 10}]}>
                  <ActivityIndicator size="large" color="#673AB7" />
                  <Text style={styles.loadingText}>加载PPT预览中...</Text>
                </View>
              )}
              
              <WebView
                key={webViewKey}
                ref={webViewRef}
                source={{
                  uri: pptUrl,
                  headers: {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                    'Cache-Control': 'no-cache',
                  }
                }}
                style={[styles.webView, !isWebViewLoaded && {opacity: 0}]}
                originWhitelist={['*']}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                cacheEnabled={false}
                thirdPartyCookiesEnabled={false}
                sharedCookiesEnabled={false}
                bounces={false}
                scrollEnabled={true}
                showsHorizontalScrollIndicator={false}
                showsVerticalScrollIndicator={false}
                onLoadStart={() => {
                  console.log('开始加载WebView:', pptUrl);
                  setIsWebViewLoaded(false);
                }}
                onLoadEnd={() => {
                  console.log('WebView加载完成');
                  // 延迟显示WebView内容，避免闪烁
                  setTimeout(() => {
                    setIsWebViewLoaded(true);
                  }, 500);
                }}
                injectedJavaScript={`
                  (function() {
                    // 防止WebView闪烁的关键设置
                    document.documentElement.style.setProperty('background-color', 'white', 'important');
                    document.body.style.setProperty('background-color', 'white', 'important');
                    document.documentElement.style.setProperty('opacity', '1', 'important');
                    document.body.style.setProperty('opacity', '1', 'important');
                    
                    // 禁用所有动画和过渡效果
                    const noTransitionStyle = document.createElement('style');
                    noTransitionStyle.innerHTML = \`
                      * {
                        transition: none !important;
                        animation: none !important;
                        will-change: auto !important;
                        -webkit-animation: none !important;
                        -webkit-transition: none !important;
                      }
                      
                      body, html {
                        background-color: #ffffff !important;
                        margin: 0 !important;
                        padding: 0 !important;
                        -webkit-transform: translate3d(0,0,0);
                        transform: translate3d(0,0,0);
                        -webkit-backface-visibility: hidden;
                        backface-visibility: hidden;
                      }
                      
                      /* 隐藏下载按钮 */
                      .download-btn, [class*="download"], .mobile-download-btn {
                        display: none !important;
                      }
                    \`;
                    document.head.appendChild(noTransitionStyle);

                    // 通知React Native组件加载完成
                    window.ReactNativeWebView.postMessage('loaded');
                    
                    return true;
                  })();
                `}
                onMessage={(event) => {
                  if (event.nativeEvent.data === 'loaded') {
                    console.log('WebView内容已准备就绪');
                    setIsWebViewLoaded(true);
                  }
                }}
                onShouldStartLoadWithRequest={(request) => {
                  // 允许任何已知的PPT相关URL加载
                  if (request.url === pptUrl || isPPTUrl(request.url)) {
                    return true;
                  }
                  
                  // 允许specialrights重定向，这是权限检查必须的
                  if (request.url.includes('specialrights')) {
                    return true;
                  }
                  
                  // 阻止非PPT页面加载，在外部浏览器打开
                  if (!isPPTUrl(request.url)) {
                    console.log('非PPT页面，尝试在浏览器打开:', request.url);
                    Linking.canOpenURL(request.url).then(supported => {
                      if (supported) {
                        Linking.openURL(request.url);
                      }
                    });
                    return false;
                  }
                  
                  return true;
                }}
              />
            </View>
            
            <View style={styles.pptNavigationControls}>
              <TouchableOpacity 
                style={styles.navButton}
                onPress={() => {
                  if (webViewRef.current) {
                    // @ts-ignore
                    webViewRef.current.injectJavaScript(`window.scrollTo(0, 0); true;`);
                  }
                }}
              >
                <Text style={styles.navButtonText}>回到顶部</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={styles.refreshButton}
                onPress={() => {
                  // 刷新WebView
                  setWebViewKey('ppt-webview-' + Date.now());
                  setIsWebViewLoaded(false);
                }}
              >
                <Text style={styles.navButtonText}>刷新</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={styles.refreshButton}
                onPress={() => openInBrowser(pptUrl)}
              >
                <Text style={styles.navButtonText}>浏览器查看</Text>
              </TouchableOpacity>
            </View>
          </View>
        ) : isGenerating ? (
          <View style={[styles.loaderContainer, {height: 200}]}>
            <ActivityIndicator size="large" color="#673AB7" />
            <Text style={styles.loadingText}>正在生成PPT，请稍候...</Text>
          </View>
        ) : null}
        
        {/* 底部占位，防止按钮遮挡内容 */}
        <View style={styles.bottomSpacer} />
      </ScrollView>

      {/* 底部按钮 */}
      <TouchableOpacity 
        style={[
          styles.generateButton,
          isGenerating && styles.generateButtonDisabled
        ]}
        onPress={handleGeneratePPT}
        disabled={isGenerating}
      >
        {isGenerating ? (
          <View style={styles.buttonLoadingContainer}>
            <ActivityIndicator size="small" color="white" />
            <Text style={styles.generateButtonText}>生成中...</Text>
          </View>
        ) : (
          <Text style={styles.generateButtonText}>一键生成PPT</Text>
        )}
      </TouchableOpacity>

      {/* 效果选择弹窗 */}
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => setModalVisible(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <TouchableOpacity 
              style={styles.closeButtonContainer}
              onPress={() => setModalVisible(false)}
            >
              <Text style={styles.closeButton}>✕</Text>
            </TouchableOpacity>
            
            <Text style={styles.modalTitle}>请选择效果</Text>
            
            <View style={styles.qualityOptions}>
              <TouchableOpacity 
                style={[
                  styles.qualityOption, 
                  tempQuality === '优质' && styles.selectedQualityOption
                ]}
                onPress={() => handleQualitySelect('优质')}
              >
                <Text style={[
                  styles.qualityOptionText,
                  tempQuality === '优质' && styles.selectedQualityOptionText
                ]}>优质</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={[
                  styles.qualityOption, 
                  tempQuality === '超优质' && styles.selectedQualityOption
                ]}
                onPress={() => handleQualitySelect('超优质')}
              >
                <Text style={[
                  styles.qualityOptionText,
                  tempQuality === '超优质' && styles.selectedQualityOptionText
                ]}>超优质</Text>
              </TouchableOpacity>
            </View>
            
            <Text style={styles.modalNote}>注：使用优质模型，内容效果和长度优秀。</Text>
            
            <TouchableOpacity 
              style={styles.confirmButton}
              onPress={handleConfirm}
            >
              <Text style={styles.confirmButtonText}>确定</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>

      {/* 内容长度选择弹窗 */}
      <Modal
        animationType="slide"
        transparent={true}
        visible={contentModalVisible}
        onRequestClose={() => setContentModalVisible(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <TouchableOpacity 
              style={styles.closeButtonContainer}
              onPress={() => setContentModalVisible(false)}
            >
              <Text style={styles.closeButton}>✕</Text>
            </TouchableOpacity>
            
            <Text style={styles.modalTitle}>请选择内容&长度</Text>
            
            <View style={styles.contentOptions}>
              {contentLengthOptions.map((option, index) => (
                <TouchableOpacity 
                  key={index}
                  style={[
                    styles.contentOption, 
                    tempContentLength === option && styles.selectedContentOption
                  ]}
                  onPress={() => handleContentLengthSelect(option)}
                >
                  <Text style={[
                    styles.contentOptionText,
                    tempContentLength === option && styles.selectedContentOptionText
                  ]}>{option}</Text>
                </TouchableOpacity>
              ))}
            </View>
            
            <TouchableOpacity 
              style={styles.confirmButton}
              onPress={handleContentConfirm}
            >
              <Text style={styles.confirmButtonText}>确定</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
    marginTop: StatusBar.currentHeight,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 50,
    backgroundColor: '#FFFFFF',
    borderBottomWidth: 1,
    borderBottomColor: '#EEEEEE',
    paddingHorizontal: 15,
  },
  backButton: {
    padding: 10,
  },
  backButtonText: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  headerTitle: {
    flex: 1,
    textAlign: 'center',
    fontSize: 18,
    fontWeight: 'bold',
    marginRight: 40,
  },
  scrollView: {
    flex: 1,
  },
  inputSection: {
    backgroundColor: '#FFFFFF',
    padding: 15,
    marginBottom: 10,
  },
  sectionTitle: {
    fontSize: 15,
    fontWeight: 'bold',
    marginBottom: 15,
  },
  required: {
    color: 'red',
  },
  themeInput: {
    height: 50,
    borderWidth: 1,
    borderColor: '#EEEEEE',
    borderRadius: 5,
    paddingHorizontal: 10,
    backgroundColor: '#FAFAFA',
  },
  qualitySection: {
    backgroundColor: '#FFFFFF',
    padding: 15,
    marginBottom: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  qualitySelector: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  qualitySelectorText: {
    fontSize: 15,
    color: '#333333',
    marginRight: 5,
  },
  qualitySelectorArrow: {
    fontSize: 16,
    color: '#999999',
  },
  lengthSection: {
    backgroundColor: '#FFFFFF',
    padding: 15,
    marginBottom: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  lengthSelector: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  lengthSelectorText: {
    fontSize: 15,
    color: '#333333',
    marginRight: 5,
  },
  lengthSelectorArrow: {
    fontSize: 16,
    color: '#999999',
  },
  styleSection: {
    backgroundColor: '#FFFFFF',
    padding: 15,
    marginBottom: 10,
  },
  styleGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    marginHorizontal: -5,
  },
  styleItem: {
    width: (width - 50) / 2,
    marginBottom: 15,
    borderRadius: 8,
    overflow: 'hidden',
    marginHorizontal: 5,
  },
  selectedStyleItem: {
    borderWidth: 2,
    borderColor: '#3478F6',
  },
  styleImageContainer: {
    height: 120,
    justifyContent: 'center',
    alignItems: 'center',
    borderTopLeftRadius: 8,
    borderTopRightRadius: 8,
    overflow: 'hidden',
  },
  styleName: {
    fontSize: 14,
    color: '#333333',
    textAlign: 'center',
    paddingVertical: 8,
    backgroundColor: '#FFFFFF',
  },
  generateButton: {
    backgroundColor: '#3DA8F5',
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
  },
  generateButtonDisabled: {
    backgroundColor: '#A8D4F5',
  },
  generateButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: 'bold',
  },
  buttonLoadingContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  bottomSpacer: {
    height: 60,
  },
  previewSection: {
    backgroundColor: '#FFFFFF',
    padding: 15,
    marginBottom: 10,
  },
  previewHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  previewControls: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  zoomButton: {
    backgroundColor: '#F2F7FF',
    paddingVertical: 5,
    paddingHorizontal: 8,
    borderRadius: 5,
    borderWidth: 1,
    borderColor: '#3DA8F5',
    marginRight: 5,
  },
  zoomButtonText: {
    color: '#3DA8F5',
    fontSize: 12,
  },
  openBrowserButton: {
    backgroundColor: '#F2F7FF',
    paddingVertical: 5,
    paddingHorizontal: 10,
    borderRadius: 5,
    borderWidth: 1,
    borderColor: '#3DA8F5',
  },
  openBrowserText: {
    color: '#3DA8F5',
    fontSize: 12,
  },
  webView: {
    flex: 1,
    backgroundColor: 'white',
    opacity: 1,
    width: '100%',
    height: '100%',
  },
  loaderContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 255, 255, 0.8)',
  },
  loadingText: {
    marginTop: 10,
    color: '#3DA8F5',
  },
  pptNavigationControls: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 10,
  },
  navButton: {
    backgroundColor: '#F2F7FF',
    paddingVertical: 8,
    paddingHorizontal: 15,
    borderRadius: 5,
    borderWidth: 1,
    borderColor: '#3DA8F5',
    flex: 1,
    marginRight: 5,
    alignItems: 'center',
  },
  navButtonText: {
    color: '#3DA8F5',
    fontSize: 14,
  },
  refreshButton: {
    backgroundColor: '#F2F7FF',
    paddingVertical: 8,
    paddingHorizontal: 15,
    borderRadius: 5,
    borderWidth: 1,
    borderColor: '#3DA8F5',
    flex: 1,
    marginLeft: 5,
    alignItems: 'center',
  },
  // 科技动感预览样式
  techPreview: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'flex-start',
    padding: 15,
  },
  techPreviewTitle: {
    fontSize: 10,
    marginBottom: 5,
  },
  techPreviewSubtitle: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  techPreviewIcon: {
    fontSize: 24,
    position: 'absolute',
    right: 10,
    bottom: 10,
  },
  // 乙已如意预览样式
  chineseStylePreview: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10,
  },
  chineseStyleTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  chineseStyleLine: {
    width: 40,
    height: 2,
    backgroundColor: '#FFFFFF',
    marginVertical: 5,
  },
  chineseStyleSubtitle: {
    fontSize: 10,
    marginTop: 5,
  },
  // 腾飞2025预览样式
  newYearPreview: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10,
  },
  newYearTitle: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  newYearSubtitle: {
    fontSize: 10,
    marginBottom: 10,
  },
  newYearBigText: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  // 大学通用预览样式
  collegePreview: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  collegeTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  collegeIcon: {
    fontSize: 24,
  },
  // 通用预览样式
  generalPreview: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10,
  },
  generalPreviewTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  generalPreviewIcon: {
    fontSize: 24,
  },
  // 选中状态样式
  checkMarkIcon: {
    position: 'absolute',
    top: 5,
    right: 5,
    width: 20,
    height: 20,
    borderRadius: 10,
    backgroundColor: '#3478F6',
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkMarkText: {
    color: '#FFFFFF',
    fontSize: 12,
    fontWeight: 'bold',
  },
  // 弹窗相关样式
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  modalContent: {
    width: '100%',
    backgroundColor: 'white',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 20,
    paddingTop: 30,
    alignItems: 'center',
  },
  closeButtonContainer: {
    position: 'absolute',
    top: 15,
    right: 15,
    zIndex: 1,
  },
  closeButton: {
    fontSize: 20,
    color: '#999',
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 30,
  },
  qualityOptions: {
    flexDirection: 'row',
    width: '100%',
    justifyContent: 'space-around',
    marginBottom: 25,
  },
  qualityOption: {
    backgroundColor: '#F2F7FF',
    paddingVertical: 12,
    paddingHorizontal: 40,
    borderRadius: 25,
    borderWidth: 0,
    borderColor: 'transparent',
  },
  selectedQualityOption: {
    backgroundColor: '#E6F0FF',
    borderWidth: 1,
    borderColor: '#3DA8F5',
  },
  qualityOptionText: {
    fontSize: 16,
    color: '#333',
  },
  selectedQualityOptionText: {
    fontWeight: 'bold',
    color: '#3DA8F5',
  },
  modalNote: {
    fontSize: 14,
    color: '#999',
    alignSelf: 'flex-start',
    marginBottom: 30,
    marginTop: 5,
  },
  confirmButton: {
    backgroundColor: '#3DA8F5',
    width: '100%',
    height: 50,
    borderRadius: 25,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 10,
  },
  confirmButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  // 内容长度选择弹窗样式
  contentOptions: {
    width: '100%',
    alignItems: 'center',
    marginBottom: 25,
  },
  contentOption: {
    backgroundColor: '#F2F7FF',
    paddingVertical: 12,
    paddingHorizontal: 40,
    borderRadius: 25,
    borderWidth: 0,
    borderColor: 'transparent',
    marginBottom: 15,
    width: '100%',
    alignItems: 'center',
  },
  selectedContentOption: {
    backgroundColor: '#E6F0FF',
    borderWidth: 1,
    borderColor: '#3DA8F5',
  },
  contentOptionText: {
    fontSize: 16,
    color: '#333',
  },
  selectedContentOptionText: {
    fontWeight: 'bold',
    color: '#3DA8F5',
  },
  // 新增样式
  browserNoticeContainer: {
    padding: 20,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#F5F9FF',
    borderRadius: 10,
    marginVertical: 15,
  },
  browserNoticeText: {
    fontSize: 16,
    color: '#333',
    textAlign: 'center',
    marginBottom: 20,
    lineHeight: 24,
  },
  successContainer: {
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#F9F9F9',
    borderRadius: 10,
  },
  successIconContainer: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: '#4CAF50',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 20,
  },
  successIcon: {
    fontSize: 40,
    color: 'white',
    fontWeight: 'bold',
  },
  successMessage: {
    fontSize: 16,
    color: '#333',
    textAlign: 'center',
    marginBottom: 20,
    lineHeight: 24,
  },
  pptInfoContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
    width: '100%',
  },
  pptInfoTitle: {
    fontSize: 15,
    fontWeight: 'bold',
    color: '#555',
  },
  pptInfoContent: {
    fontSize: 15,
    color: '#333',
    flex: 1,
  },
  browserViewButton: {
    backgroundColor: '#673AB7',
    paddingVertical: 15,
    paddingHorizontal: 20,
    borderRadius: 25,
    width: '100%',
    alignItems: 'center',
    marginTop: 20,
    marginBottom: 15,
  },
  browserViewButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  newPptButton: {
    backgroundColor: 'white',
    paddingVertical: 15,
    paddingHorizontal: 20,
    borderRadius: 25,
    width: '100%',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#673AB7',
  },
  newPptButtonText: {
    color: '#673AB7',
    fontSize: 16,
    fontWeight: 'bold',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#fff',
  },
  errorTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#d32f2f',
    marginBottom: 10,
  },
  errorDesc: {
    fontSize: 14,
    color: '#666',
    marginBottom: 20,
    textAlign: 'center',
  },
  retryButton: {
    backgroundColor: '#3DA8F5',
    paddingVertical: 12,
    paddingHorizontal: 20,
    borderRadius: 25,
    marginBottom: 10,
    alignItems: 'center',
    width: 200,
  },
  retryButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  browserButton: {
    backgroundColor: '#673AB7',
    paddingVertical: 12,
    paddingHorizontal: 20,
    borderRadius: 25,
    alignItems: 'center',
    width: 200,
  },
  browserButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default PptGenerationScreen; 